import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Proxy;
import java.net.Socket;

/**
 * @author cxx
 * @create 2020-04-20 10:56
 **/
public class ProxyTarget {


    public static <T> T instance(String beanName,Class<T> target){

       return (T) Proxy.newProxyInstance (target.getClassLoader (),new Class[]{target},(proxy,method,args)->{

           if (method.getDeclaringClass ().isAssignableFrom (Object.class)) {
              return method.invoke (target,args);
           }

           RequestObject requestObject = new RequestObject ();
           requestObject.setClz (target.getClass ());
           requestObject.setMethod (method.getName ());
           requestObject.setArgs (args);
           requestObject.setTarget (beanName);

           Socket socket = new Socket ("127.0.0.1",9090);

           ObjectOutputStream outputStream = new ObjectOutputStream (socket.getOutputStream ());
           outputStream.writeObject (requestObject);
           outputStream.flush ();
           InputStream inputStream = socket.getInputStream ();
           ObjectInputStream ois = new ObjectInputStream (inputStream);
           Object responseObj = ois.readObject ();
           if (responseObj instanceof ResponseObject){
               return ((ResponseObject) responseObj).getTarget ();
           }

           return null;
        });

    }


}
